package com.dfs.parent.gateway.filter;

import com.dfs.parent.common.core.constant.GrayConstant;
import com.dfs.parent.gateway.props.GrayProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * @Description TODO
 * @Author dahong
 * @Date 2025/8/5 14:32
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GrayFilter implements GlobalFilter, Ordered {
    private final GrayProperties grayProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 检查灰度配置是否启用
        if (grayProperties.getEnabled()==null || !grayProperties.getEnabled()) {
            return chain.filter(exchange);
        }
        // 从请求头获取灰度标记
        String grayTag = exchange.getRequest().getQueryParams().getFirst("aa");
        if ("true".equals(grayTag)) {
            // 将灰度标记存入请求上下文
            // 关键步骤：将exchange存入ClientRequest的属性中
            ServerHttpRequest newRequest = exchange.getRequest().mutate()
                    .header(GrayConstant.GRAY_HEADER_TAG, GrayConstant.GRAY_HEADER_TAG_VALUE_TRUE)
                    .build();

// 4. 重建Exchange并设置属性（兼容Spring Boot 2.x的写法）
            ServerWebExchange newExchange = exchange.mutate()
                    .request(newRequest)
                    .build();
            return chain.filter(newExchange);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 1;
    }
}